package com.enba.boot.log.strategy;

import com.enba.boot.log.LogHelper;
import com.enba.boot.log.properties.LogProperties;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

public class MySqlStrategy implements LogHelper {

  @Autowired private JdbcTemplate jdbcTemplate;
  private final LogProperties logProperties;

  public MySqlStrategy(LogProperties logProperties) {
    this.logProperties = logProperties;
  }

  @Override
  public void log(String message) {
    String sql = "INSERT INTO " + logProperties.getTableName() + " (message) VALUES (?)";
    jdbcTemplate.update(sql, message);
  }

  @PostConstruct
  public void init() {
    // 检查表是否存在，不存在则创建
    if (!checkTableExists(logProperties.getTableName())) {
      createLogTable(logProperties.getTableName());
    }
  }

  /**
   * 检查表是否存在
   *
   * @param tableName 表名
   * @return true 表存在，false 表不存在
   */
  public boolean checkTableExists(String tableName) {
    String sql =
        "SELECT COUNT(*) FROM information_schema.tables "
            + "WHERE table_schema = DATABASE() AND table_name =?";
    Integer count = jdbcTemplate.queryForObject(sql, Integer.class, tableName);
    return count != null && count > 0;
  }

  /** 创建日志表 */
  public void createLogTable(String tableName) {
    String sql =
        "CREATE TABLE "
            + tableName
            + " ("
            + "  `id` int NOT NULL AUTO_INCREMENT,"
            + "  `message` varchar(2048) NOT NULL,"
            + "  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,"
            + "  PRIMARY KEY (`id`)"
            + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci";
    jdbcTemplate.update(sql);
  }
}
